# 迭代和列表解析

## 迭代
d=iter([1,2,3])
next(d)
next(d)
next(d)
next(d)     #StopIteration

dic={'name':'John','age':12}
d=iter(dic)
next(d)     #key
dic={'name':'John','age':12}
d=iter(dic.keys())
next(d)     #keys
dic={'name':'John','age':12}
d=iter(dic.values())
next(d)     #values
dic={'name':'John','age':12}
d=iter(dic.items())
next(d)     #(key,value)s

#next实际调用的是 __next()__ 方法的内容

## 列表解析
t=[1,2,3,4]
[x+10 for x in range(10) if x%2==0]         #带条件的 [10, 12, 14, 16, 18]
[x+y for x in (10,20) for y in (1,2,3)]     #多层嵌套 [11, 12, 13, 21, 22, 23]

(x for x in range(10))              #<generator object <genexpr> at 0x000001AFACA92FC0>
tuple(x*2 for x in range(5))        #(0, 2, 4, 6, 8)
{x for x in range(10)}              #{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
{x:ord(x) for x in 'abcd'}          #{'a': 97, 'b': 98, 'c': 99, 'd': 100}
[x for x in open(r'./doc/code.txt',encoding='UTF_8')]   #['one 第一行\n', 'two 第二行\n', 'three 第三行']

all([0,1,2,3,4,5])      #False,全部为真才返回True
any([0,1,2,3,4])        #True,有一个为真即为真
sum([0,1,2,3,4])
sorted([4,2,6,1,3,6])
min([4,2,6,1,3,6])
max([4,2,6,1,3,6])
min(open(r'./doc/code.txt',encoding='UTF_8'))
max(open(r'./doc/code.txt',encoding='UTF_8'))
list(open(r'./doc/code.txt',encoding='UTF_8'))
tuple(open(r'./doc/code.txt',encoding='UTF_8'))
set(open(r'./doc/code.txt',encoding='UTF_8'))
a,b,c=open(r'./doc/code.txt',encoding='UTF_8')
a,b,c       #('one 第一行\n', 'two 第二行\n', 'three 第三行')


## zip,map,filter生成可迭代
x=zip((1,2,3),(10,20,30))
x           #<zip at 0x14e8b2ebbc8>
next(x)
x=zip((1,2),'ab',[5,6])
next(x)     #(1, 'a', 5)
next(x)     #(2, 'b', 6)
next(x)     #StopIteration

x=map(ord,'abc')
next(x)     #97
next(x)     #98
next(x)     #99
next(x)     #StopIteration
list(map(ord,'abc'))        #[97, 98, 99]

x=filter(bool,(1,-1,0,'ab','',(),{},(1,2),{1,2},{'a':1}))
x           #<filter at 0x14e8b33f898>
next(x)     #1
list(x)     #[-1, 'ab', (1, 2), {1, 2}, {'a': 1}]















